#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "Log.hpp"

#include <unordered_map>

const std::string defaultWordPath = "./source/word.txt";

class Interpret
{
public:
    Interpret(const std::string &wordpath = defaultWordPath)
        : _wordpath(wordpath)
    {
        LoadDict();
        Parse();
    }

    void LoadDict()
    {
        std::string line;
        std::ifstream file(_wordpath);
        if (file.is_open()) // 如果打开成功了就一行一行的读取出来
        {
            while (std::getline(file, line))
            {
                lines.push_back(line);
            }
            file.close();
        }
        else
        {
            lg.LogMessage(Error, "open file fail\n");
        }
        lg.LogMessage(Debug, "Load dict txt success, path:%s\n", _wordpath.c_str());
    }

    void Parse() // 解析
    {
        for (const auto &line : lines)
        {
            int pos = line.find(" ");
            std::string word = line.substr(0, pos);
            int rpos = line.rfind(".");
            std::string chinese = line.substr(rpos + 1, line.size());
            dicts.insert(make_pair(word, chinese));
        }
    }

    void PrintDebug()
    {
        for (const auto &dict : dicts)
        {
            std::cout << dict.first << ":" << dict.second << std::endl;
        }
    }

    std::string Excute(const std::string &word)
    {
        auto iter = dicts.find(word);
        if (iter != dicts.end())
        {
            return dicts[word];
        }
        else
            return "unknown";
    }

private:
    std::unordered_map<std::string, std::string> dicts;
    std::string _wordpath;
    std::vector<std::string> lines;
};
